/**
 * @file 工具类
 * @module libs/tools
 * @author 月落 <yueluo.yang@qq.com>
 */

/**
 * @requires libs/storgae - 本地存储
 */
import storage from './storage';

/**
 * @description 检测当前版本库是否支持云能力
 * @returns {boolean}
 */
function checkCloudIsSupport () {
  return wx.cloud;
}

/**
 * @description 获取导航栏高度
 * @returns {number}
 */
function getNavBarHeight () {
   // 获取设备信息
   const { statusBarHeight } = wx.getSystemInfoSync();
   // 获取右上胶囊按钮的位置信息
   const { height, top, bottom } = wx.getMenuButtonBoundingClientRect();

   // 构造胶囊信息
   const capsulePos = {
     top: top - statusBarHeight,
     bottom: bottom - height - statusBarHeight,
   };
   // 构造导航栏高度
   const navBarHeight =  bottom + capsulePos.top;

  return navBarHeight + statusBarHeight;
}

/**
 * @description 获取右侧胶囊位置
 * @returns {object}
 */
function getCapsulePos () {
  // 获取设备信息
  const { statusBarHeight, screenWidth } = wx.getSystemInfoSync();
  // 获取右上胶囊按钮的位置信息
  const { height, top, right, bottom } = wx.getMenuButtonBoundingClientRect();

  // 构造胶囊信息
  const capsulePos = {
    top: top - statusBarHeight,
    bottom: bottom - height - statusBarHeight,
    right: screenWidth - right
  };

  return capsulePos;
}

/**
 * @description 检测用户是否登录
 * @returns {boolean}
 */
function checkUserIsLogin () {
  return storage.get('user');
}

/**
 * @description 展示loading
 * @returns {void}
 */
function showLoading () {
  wx.showLoading({
    title: 'loading',
  });
}

/**
 * @description 隐藏loading
 * @returns {void}
 */
function hideLoading () {
  try {
    wx.hideLoading({
      success: () => {},
      fail: () => {}
    });
  } catch (error) {
    console.log(error);
  }
}

/**
 * @description 吐司提示
 * @param {string} title - 提示信息
 * @returns {void}
 */
function showToast (title) {
  wx.showToast({
    icon: 'none',
    title,
  });
}

/**
 * @description 获取事件对象中数据
 * @param {object} e - 事件源对象 
 * @returns {void}
 */
function getEventDetail (e) {
  const dataset = e.currentTarget.dataset;
  return Object.keys(dataset).length ? dataset : e.detail;
}

// 导出工具类
export default {
  checkCloudIsSupport,
  checkUserIsLogin,
  getNavBarHeight,
  getCapsulePos,
  showLoading,
  hideLoading,
  showToast,
  getEventDetail
}